package com.bagua.sbbcshop.auth;

import com.bagua.sbbcshop.cache.CacheManager;
import com.bagua.sbbcshop.cache.memory.MemoryCacheManager;
import com.bagua.sbbcshop.config.ApiConfig;
import com.bagua.sbbcshop.tool.JDKencMD5_32;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 通过cache存储和验证token
 * @author xhou
 */
@Component
public class TokenManager {


    private CacheManager tokenCache=new MemoryCacheManager();

    /**
     * 通过 Token 实体在 Redis 中创建一个 Token
     * @param token
     * @return tokenKey
     */
    public String createToken(Token token) {
        String cipherText  = JDKencMD5_32.getMD5Str(String.valueOf(token.getUserId() + token.getMobile().hashCode() + token.getLoginId().hashCode() + token.getOpenid().hashCode()));
         tokenCache.getCache(ApiConfig.SBBC_TOKEN).put(cipherText,token);
        return cipherText;
    }

    /**
     * 通过 key 获取Token
     *
     * @return Token 实体
     */
    public Token getToken(HttpServletResponse response) {
        String header = response.getHeader(ApiConfig.JWT_TOKEN_HEADER_PARAM);
        Token token=null;
        String tokenKey = header.replaceAll(ApiConfig.JWT_TOKEN_HEADER_PREFIX, "");
        //如果key长度超过md5码长度即解码返回
        if (StringUtils.isNotBlank(tokenKey)) {
            token = (Token) tokenCache.getCache(ApiConfig.SBBC_TOKEN).get(tokenKey);
            return token;
        }
        return token;
    }

    /**
     * 判断Token 是否有效
     *
     * @param tokenKey
     * @return boolean 值
//     */
    public boolean checkToken(String tokenKey) {
        if (tokenKey == null) {
            return false;
        }
        Object token = tokenCache.getCache(ApiConfig.SBBC_TOKEN).get(tokenKey);
        if (token == null) {
            return false;
        }
        //如果验证成功，说明此用户进行了一次有效操作，延长token的过期时间,加一分钟
//        Long minutes = redisTokenTemplate.getExpire(tokenKey, TimeUnit.MINUTES);
//        redisTokenTemplate.expire(tokenKey, minutes + 1L, TimeUnit.MINUTES);
        return true;
    }

    /**
     * 清除原token操作
     * @param request
     * @return
     */
    public boolean cleanToken(HttpServletRequest request) {
        String header = request.getHeader(ApiConfig.JWT_TOKEN_HEADER_PARAM);
        String tokenKey = header.replace(ApiConfig.JWT_TOKEN_HEADER_PREFIX, "");
//        if (!checkToken(tokenKey, "")) {
//            return false;
//        }
        tokenCache.getCache(ApiConfig.SBBC_TOKEN).remove(tokenKey);
        return true;
    }
}
